package com.spddr.pmos.cxf.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.google.common.collect.Table;
import com.google.common.collect.TreeBasedTable;
import com.spddr.pmos.cxf.JaxrsUnitNhq;
import com.spddr.pmos.jpa.UnitNhq;
import com.spddr.pmos.jpa.UnitNhqId;
import com.spddr.pmos.repos.UnitNhqRepos;

import cn.seqdata.echarts.Option;
import cn.seqdata.echarts.axis.CategoryAxis;
import cn.seqdata.echarts.axis.ValueAxis;
import cn.seqdata.echarts.series.Line;

@Service
public class JaxrsUnitNhqImpl implements JaxrsUnitNhq {
	@Autowired
	private UnitNhqRepos repository;

	@Override
	public JpaRepository<UnitNhq, UnitNhqId> getRepository() {
		return repository;
	}

	@Override
	public List<UnitNhq> findByUnit(long unit) {
		return repository.findByIdUnit(unit);
	}

	@Override
	public void saveByUnit(long unit, List<UnitNhq> entities) {
		repository.save(entities.stream()
				.peek(x -> x.getId()
						.setUnit(unit))
				.collect(Collectors.toList()));
	}

	@Override
	public void deleteByUnit(long unit) {
	}

	@Override
	public Option chart(long unit) {
		Option option = new Option();
		option.legend()
				.data("机组效率曲线");
		option.title()
				.show(false);

		Table<BigDecimal, BigDecimal, Double> table = TreeBasedTable.create();
		repository.findByIdUnit(unit)
				.forEach(x -> table.put(x.getId()
						.getDropHeight(),
						x.getId()
								.getPower(),
						x.getFlux()));

		CategoryAxis xAxis = new CategoryAxis().show(true);
		xAxis.data()
				.addAll(table.columnKeySet());
		option.xAxis(xAxis);

		option.yAxis(new ValueAxis().show(true));

		for (BigDecimal power : table.rowKeySet()) {
			Line line = new Line();
			Map<BigDecimal, Double> rows = table.row(power);

			for (BigDecimal hh : table.columnKeySet()) {
				line.data()
						.add(rows.getOrDefault(hh, Double.NaN));
			}

			option.series()
					.add(line);
		}

		return option;
	}
}
